import {reactive, SimpleFunction, watch} from "plain-design-composition";
import {MicroApp, Page} from "plain-micro-application";
import {nav} from "@/micro/nav/nav";
import {injectRequestSingleApplicationPage} from "@/micro/nav/components/useSingleApplicationRender";
import {delay} from "plain-utils/utils/delay";

export function useMicroNavigatorPageSingleCase({loading}: { loading: { loading: boolean } }) {

    const {requestSingleApplicationPage} = injectRequestSingleApplicationPage()

    const state = reactive({
        // 当前子应用是否为单例，单例的话就不渲染page节点
        isAppSingle: false,
        // 当前页面为单例的时候，页面隐藏的时候的路由的fullPath
        prevFullPath: null as null | string,
    })

    const onPageInit = ({app, props, entryPublicPath}: { app: MicroApp, props: { show?: boolean, page: Page }, entryPublicPath: string }) => {
        /*单例模式，只要是这个子应用的页面，只用一个div显示*/
        state.isAppSingle = true
        const singleApplicationPage = requestSingleApplicationPage(app)
        let closePage: SimpleFunction | null = null;
        watch(() => props.show, async val => {
            if (!!closePage) {
                closePage()
                closePage = null
            }
            if (!!val) {
                // await delay(100)
                const page: Page = !!state.prevFullPath ? nav.utils.createPage({path: state.prevFullPath}) : props.page
                // console.log(page)
                // console.log('apply', state.prevFullPath)
                closePage = await singleApplicationPage.showPage(page)
            } else {
                if (loading.loading) {
                    /*正在loading证明页面还没加载完，此时不监听url变化*/
                    return
                }
                /*监听url变化，当前page内的页面是单例应用的路由，所以page（隐藏）之前记录当前的fullPath，page显示的时候重新打开这个fullPath*/
                state.prevFullPath = (location.pathname + location.search).replace(new RegExp(`^/?${entryPublicPath}/?`), "/")
                // console.log('store', state.prevFullPath)
            }
        }, {immediate: true})

        return () => !!closePage && closePage()
    }

    return {
        onPageInit,
        singleCaseState: state,
    }
}
